<template>
	<a-form ref="mobile" :model="formData" :rules="formRules" layout="vertical" class="form-box">
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="应用名称" name="htmlName">
					<a-input v-model:value="formData.htmlName" placeholder="请输入应用名称" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="应用来源" name="appSource">
					<a-select v-model:value="formData.appSource" placeholder="请选择应用来源"
						:options="tool.dictList('APP_SOURCE')" allow-clear />
				</a-form-item>
			</a-col>
			<!-- <a-col :span="8">
				<a-form-item label="版本号" name="appVersion">
					<a-input v-model:value="formData.appVersion" placeholder="请输入版本号" />
				</a-form-item>
			</a-col> -->
			<a-col :span="8">
				<a-form-item label="移动端appId" name="htmlAppId">
					<a-input v-model:value="formData.htmlAppId" disabled />
				</a-form-item>
			</a-col>
		</a-row>
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="版本号" name="appVersion">
					<a-input v-model:value="formData.appVersion" placeholder="请输入版本号" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="版本说明" name="appVersionNote">
					<a-input v-model:value="formData.appVersionNote" placeholder="请输入版本说明" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="应用访问URL地址" name="appUrl">
					<a-input v-model:value="formData.appUrl" placeholder="请输入应用访问URL地址" />
				</a-form-item>

			</a-col>

		</a-row>
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="参数信息" name="appParam">
					<a-textarea v-model:value="formData.appParam" placeholder="参数信息" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="logo" name="appLogo">
					<div class="upload-box">
						<a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card"
							class="avatar-uploader" :customRequest="customRequest" :accept="fileImgType"
							:before-upload="beforeUpload" @change="handleChange" @preview="handlePreview">
							<div v-if="fileList?.length == 0">
								<plus-outlined></plus-outlined>
								<div class="ant-upload-text">上传图片</div>
							</div>
						</a-upload>
						<div class="annotation">
							<div class="tit1">*注</div>
							<div>1.应用logo需要满足UI/UE规范;</div>
							<div>2.需要上传.png/.jpg/.jpeg格式文件;</div>
							<div>3.文件大小为不超过200K;</div>
						</div>
					</div>
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="app状态" name="appStatus">
					<a-select v-model:value="formData.appStatus" placeholder="请选择" :options="statusData"
						:field-names="{ label: 'name', value: 'key' }" allow-clear />
				</a-form-item>
			</a-col>

		</a-row>
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="名单权限" name="appPermission">
					<a-radio-group v-model:value="formData.appPermission" :options="radioOption" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="是否展示图标" name="isHideLogo">
					<a-radio-group v-model:value="formData.appIsHideLogo" :options="radioOption11" name="isHideLogo" />
				</a-form-item>
			</a-col>
		</a-row>
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="imageUrl" />
		</a-modal>
	</a-form>
</template>

<script setup name="MobileForm">
import fileApi from '@/api/dev/fileApi'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import sysConfig from '@/config/index'
import { cloneDeep } from 'lodash-es'
const fileUrl = import.meta.env.VITE_FILE_URL

const fileImgType = '.jpg,.png,.jpeg,'
const mobile = ref()
// 表单数据
const formData = ref({
	htmlName: '',
	appSource: '',
	appVersion: '',
	appVersionNote: '',
	appUrl: '',
	appParam: '',
	appLogo: '',
	appStatus: '',
	appPermission: '',
	htmlAppId: '',
	appIsHideLogo: ''
})
const statusData = inject('statusData')
// 环境 https://生产  http://测试
// const circum = computed(() => {
// 	return sysConfig.NODE_ENV === 'production' ? 'https://' : 'http://'
// })
// 兼容行option
const validatePass = async (_, value) => {
	const reg = /^([1-9]\d|[1-9])(\.([0-9]){1,3}){1,9}$/
	if (!value) {
		return Promise.reject('请输入版本号')
	}
	if (!reg.test(value)) {
		return Promise.reject('请输入正确的版本号')
	}
	return Promise.resolve()
}
const valiUrl = async (_, value) => {
	if (!value) {
		return Promise.reject('请输入应用访问URL地址')
	}
	if (/[\u4E00-\u9FA5]/g.test(value)) {
		return Promise.reject('不能输入汉字!')
	}
	// if (/(http|https):\/\/\S*/.test(value)) {
	// 	return Promise.reject('必须是http和https开头!')
	// }
	return Promise.resolve()
}
const radioOption = [
	{ label: '全国', value: '0' },
	{ label: '白名单', value: '1' }
]
const radioOption11 = [
{ label: '是', value: '1' },
	{ label: '否', value: '0' },
	
]
// 默认要校验的
const formRules = {
	appSource: [{ required: true, message: '请选择应用来源', trigger: 'blur' }],
	appVersion: [{ required: true, validator: validatePass, tirgger: 'blur' }],
	appVersionNote: [{ required: true, message: '请输入版本说明', trigger: 'blur' }],
	appUrl: [{ required: true, validator: valiUrl, tirgger: 'blur' }],
	// param: [{ required: true, message: '请输入参数信息', trigger: 'blur' }],
	appLogo: [{ required: true, message: '请选择logo', trigger: 'blur' }]
}

const fileList = ref([])
const loading = ref(false)
const imageUrl = ref('')
let previewVisible = ref(false)

/*变更编辑  开始*/
const version = inject('version')
const editDate = JSON.parse(tool.session.get('editDateCL'))
Object.keys(formData.value).forEach((v) => {
	formData.value[v] = editDate[v]
})
formData.value.appLogo = ''
// fileList.value = formData.value.appLogo ? JSON.parse(formData.value.appLogo) : []
// fileList.value.forEach((item) => {
// 	item.url = `${fileUrl}/${item.url}`
// })
/*变更编辑  结束*/
// 自定义上传
const customRequest = (file) => {
	// 后端需要接受的参数是 formData数据，
	const form = new FormData()
	form.append('file', file.file)
	fileApi
		.uploadCosReturnUrlPub(form)
		.then((res) => {
			let arr = [{ name: file.file.name, url: res }]
			formData.value.appLogo = JSON.stringify(arr)
			file.onSuccess(res, file.file)
			file.status = 'done'
		})
		.catch((err) => {
			setTimeout(() => {
				file.onError()
			}, 1000)
		})
}
const getBase64 = (img, callback) => {
	const reader = new FileReader()
	reader.addEventListener('load', () => callback(reader.result))
	reader.readAsDataURL(img)
}
const handleChange = (info) => {
	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}
	if (info.file.status === 'done') {
		// Get this url from response in real world.
		getBase64(info.file.originFileObj, (base64Url) => {
			imageUrl.value = base64Url
			loading.value = false
		})
	}
	if (info.file.status === 'error') {
		loading.value = false
		fileList.value = []
		// message.error('upload error')
	}
	if (info.file.status === 'removed') {
		formData.value.appLogo = ''
	}
}
const beforeUpload = (file) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
	if (!isJpgOrPng) {
		message.error('图片类型不对')
	}
	const isLt2K = file.size / 1024 < 200
	if (!isLt2K) {
		message.error('图片大小不超过200K')
	}
	return isJpgOrPng && isLt2K
}
const handlePreview = () => {
	previewVisible.value = true
}
const handleCancel = () => {
	previewVisible.value = false
}

// 表单验证
const handleValidate = () => {
	return new Promise((resolve, reject) => {
		// if (!formData.value.appUrl.includes('http')) {
		// 	formData.value.appUrl = circum.value + formData.value.appUrl
		// }
		resolve(formData.value)
		// mobile.value
		// 	.validate()
		// 	.then(() => {
		// 		console.log('成功')
		// 		resolve(formData.value)
		// 	})
		// 	.catch(() => {
		// 		console.log('失败')
		// 		resolve(false)
		// 	})
	})
}
defineExpose({ handleValidate, formData })
</script>


<style lang="less" scoped>
.form-box {
	margin-top: 14px;

	.upload-box {
		display: flex;

		.annotation {
			font-size: 12px;
			color: rgb(150, 150, 150);
			line-height: 22px;
			margin-left: 10px;

			.tit1 {
				color: rgb(194, 0, 0);
			}
		}
	}

	&-inp {
		border-radius: 4px;
		border: 1px solid rgb(206, 206, 206);
	}
}
</style>
<style>
.avatar-uploader>.ant-upload {
	width: 104px;
	height: 104px;
}

.ant-upload-select-picture-card i {
	font-size: 32px;
	color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
	margin-top: 8px;
	color: #666;
}

.upload-box>.ant-upload-picture-card-wrapper {
	width: unset;
}
</style>
